import request from '@/utils/request'

export interface UploadResponse {
  url: string
  size: number
}

export interface OssInfo {
  id: string
  url: string
  createDate: string
}

/**
 * 上传文件到OSS (使用本地附件服务)
 */
export const uploadFile = (file: File, siteId?: number): Promise<UploadResponse> => {
  const formData = new FormData()
  formData.append('file', file)
  if (siteId) {
    formData.append('siteId', siteId.toString())
  }

  return request({
    url: '/admin/attachment/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    // 转换响应格式以匹配OSS接口
    if (response && response.data && response.data.url) {
      return {
        url: response.data.url,
        size: response.data.size || 0
      }
    }
    throw new Error('上传失败：响应格式错误')
  })
}

/**
 * 获取OSS文件信息
 */
export const getOssInfo = (id: string): Promise<OssInfo> => {
  return request({
    url: `/oss/file/${id}`,
    method: 'get'
  })
}

/**
 * 分页查询OSS文件
 */
export const getOssPage = (params: any) => {
  return request({
    url: '/oss/file/page',
    method: 'get',
    params
  })
}

/**
 * 获取云存储配置信息
 */
export const getOssConfig = () => {
  return request({
    url: '/oss/file/info',
    method: 'get'
  })
}

/**
 * 保存云存储配置信息
 */
export const saveOssConfig = (data: any) => {
  return request({
    url: '/oss/file',
    method: 'post',
    data
  })
}
